package com.innovation.chengzhangriji.ui;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.innovation.chengzhangriji.Baby;
import com.innovation.chengzhangriji.Config;
import com.innovation.chengzhangriji.R;
import com.innovation.chengzhangriji.database.DatabaseManager;
import com.innovation.chengzhangriji.http.Client;
import com.innovation.chengzhangriji.preferences.LoginInfo;
import com.innovation.chengzhangriji.ui.widget.CuteTextView;
import com.innovation.chengzhangriji.util.BabyUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class HistoryGalleryActivity extends BaseActivity {

    private int index;

    private String[] urls;

    private long[] createTSs;

    private int[] states;

    private String[] themes;
    private ArrayList<Bitmap> listbitmap;
    private String[] texts;
    private ImageView imageView,imageView_tosave;
    private Bitmap image;
    private ViewPager viewPager;
    // private boolean isLocal;

    private DisplayImageOptions options;
    private AlertDialog alertDialog;
    private CuteTextView mTextDate;
    private CuteTextView mTextAge;
    private CuteTextView mTextTheme;

    private FrameLayout mLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        String thumbUrl = bundle.getString("url");
        urls = bundle.getStringArray("urls");
        createTSs = bundle.getLongArray("createTSs");
        themes = bundle.getStringArray("themes");
        states = bundle.getIntArray("states");
        texts = bundle.getStringArray("texts");
        // isLocal = bundle.getBoolean("local");
        listbitmap = new ArrayList<Bitmap>();
        for (int i = 0; i < urls.length; i++) {
            Log.d("地址", "" + urls[i]);
            if (thumbUrl.equals(urls[i])) {
                index = i;
            }
        }
        setOptions();
        setupLayout();

        if (!TextUtils.isEmpty(themes[index])) {
            Log.d("主题", "" + themes[index]);
            mTextTheme.setText('(' + themes[index] + ')');
        } else {
            mTextTheme.setText("");
        }
        if (!TextUtils.isEmpty(texts[index])) {
            mTextTheme.setText(mTextTheme.getText() + texts[index]);
        } else {
            mTextTheme.setText(mTextTheme.getText());
        }
        if (TextUtils.isEmpty(mTextTheme.getText())) {
            mLayout.setVisibility(View.INVISIBLE);
        } else {
            mLayout.setVisibility(View.VISIBLE);
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.SIMPLIFIED_CHINESE);
        Date date = new Date(createTSs[index]);
        if (!TextUtils.isEmpty(sf.format(date))) {
            mTextDate.setText(sf.format(date));
        }
        // 判断状态,计算年龄
        LoginInfo info = Config.getLoginInfo(HistoryGalleryActivity.this);
        if (info == null) {
            return;
        }
        Baby baby = DatabaseManager.getInstance(HistoryGalleryActivity.this).queryBaby(info.getUserID(), info.getBabyID());
        String age = BabyUtil.getBabyDay(baby, states[index], createTSs[index]);
        if (!TextUtils.isEmpty(age)) {
            mTextAge.setText(age);
        }

    }

    private void setupLayout() {
        setContentView(R.layout.activity_history_gallery);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
//        viewPager.setOffscreenPageLimit(0);

        viewPager.setAdapter(new PhotoPagerAdapter());
        viewPager.setCurrentItem(index);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (!TextUtils.isEmpty(themes[position])) {
                    Log.d("主题", "" + themes[position]);
                    mTextTheme.setText('(' + themes[position] + ')');
                } else {
                    mTextTheme.setText("");
                }
                if (!TextUtils.isEmpty(texts[position])) {
                    mTextTheme.setText(mTextTheme.getText() + texts[position]);
                } else {
                    mTextTheme.setText(mTextTheme.getText());
                }
                if (TextUtils.isEmpty(mTextTheme.getText())) {
                    mLayout.setVisibility(View.INVISIBLE);
                } else {
                    mLayout.setVisibility(View.VISIBLE);
                }
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.SIMPLIFIED_CHINESE);
                Date date = new Date(createTSs[position]);
                if (!TextUtils.isEmpty(sf.format(date))) {
                    mTextDate.setText(sf.format(date));
                }
                // 判断状态,计算年龄
                LoginInfo info = Config.getLoginInfo(HistoryGalleryActivity.this);
                if (info == null) {
                    return;
                }
                Baby baby = DatabaseManager.getInstance(HistoryGalleryActivity.this).queryBaby(info.getUserID(), info.getBabyID());
                String age = BabyUtil.getBabyDay(baby, states[position], createTSs[position]);
                if (!TextUtils.isEmpty(age)) {
                    mTextAge.setText(age);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        mTextDate = (CuteTextView) findViewById(R.id.text_date);
        mTextAge = (CuteTextView) findViewById(R.id.text_age);
        mTextTheme = (CuteTextView) findViewById(R.id.text_theme);
        mLayout = (FrameLayout) findViewById(R.id.layout_bottom);

    }

    private void setOptions() {
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.ic_photo_empty)    //在ImageView加载过程中显示图片
                .showImageForEmptyUri(R.drawable.ic_photo_empty)  //image连接地址为空时
                .showImageOnFail(R.mipmap.icon_download_failed)  //image加载失败
                        // .cacheInMemory(true)  //加载图片时会在内存中加载缓存
                .cacheOnDisk(true)   //加载图片时会在磁盘中加载缓存
                .build();

    }

    private class PhotoPagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            if (urls == null) {
                return 0;
            }
            return urls.length;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View itemView;
            itemView = inflater.inflate(R.layout.item_history_gallery_photo, container, false);
             imageView = (ImageView) itemView.findViewById(R.id.image_photo);

            if (urls[position].startsWith("/")) {
                ImageLoader.getInstance().displayImage("file://" + urls[position], imageView, options, null);
            } else {
                ImageLoader.getInstance().displayImage(urls[position], imageView, options, null);
            }
//            listbitmap.add(((BitmapDrawable)imageView.getDrawable()).getBitmap());
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
            imageView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    final ImageView iv = new ImageView(HistoryGalleryActivity.this);
                    ImageLoader.getInstance().displayImage(urls[viewPager.getCurrentItem()], iv, options, null);
                    alertDialog = new AlertDialog.Builder(HistoryGalleryActivity.this).create();
                    alertDialog.show();
                    alertDialog.getWindow().setGravity(Gravity.BOTTOM);
                    alertDialog.getWindow().setContentView(R.layout.dialog_savephoto);
                    alertDialog.getWindow()
                            .findViewById(R.id.tv_phote_cancle)
                            .setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    alertDialog.dismiss();
                                }
                            });
                    alertDialog.getWindow()
                            .findViewById(R.id.tv_phote_save)
                            .setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
//                                    image = ((BitmapDrawable) imageView.getDrawable()).getBitmap();

                                    image = ((BitmapDrawable) iv.getDrawable()).getBitmap();
                                    Log.d("2asd", "" + image);
                                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    String date = df.format(new Date());
                                    date = date.substring(0, 4) + date.substring(5, 7) + date.substring(8, 10) + "_" + date.substring(11, 13) + date.substring(14, 16) + date.substring(17, 19);
                                    String nowdate = Environment.getExternalStorageDirectory() + "/DCIM/Camera/" + date + ".jpg";
                                    try {
                                        File myCaptureFile = new File(nowdate);
                                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                                        image.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                                        bos.flush();
                                        bos.close();
                                    } catch (Exception e) {

                                    }
                                    /*FileOutputStream b = null;
                                    try {
                                        b = new FileOutputStream(nowdate);
                                        image.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                                    } catch (FileNotFoundException e) {
                                        e.printStackTrace();
                                    } finally {
                                        try {
                                            b.flush();
                                            b.close();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }*/
                                    alertDialog.dismiss();
                                    tipShow("已保存到系统相册");

                                }
                            });
                    return false;
                }
            });


            // 处理本地图片
            /*DisplayMetrics dm = getResources().getDisplayMetrics();
            Log.d("屏幕宽", "" + dm.widthPixels);
            Log.d("屏幕高", "" + dm.heightPixels);
            // 获得图片宽和高
            BitmapFactory.Options op = new BitmapFactory.Options();
            op.inJustDecodeBounds = true;
            Bitmap bmp = BitmapFactory.decodeFile(urls[position], op);
            Log.d("图片宽", "" + op.outWidth);
            Log.d("图片高", "" + op.outHeight);
            if (dm.widthPixels * 1.0f / op.outWidth < (dm.heightPixels * 1.0f - 48 * 2 * dm.density) / op.outHeight) {
                if (dm.widthPixels >= op.outWidth) {
                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    lp.addRule(RelativeLayout.CENTER_IN_PARENT);
                    imageView.setLayoutParams(lp);
                } else {
                    int h = (int) (op.outHeight * dm.widthPixels * 1.0f / op.outWidth);
                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, h);
                    lp.addRule(RelativeLayout.CENTER_IN_PARENT);
                    imageView.setLayoutParams(lp);
                }
            } else {
                if (dm.heightPixels >= op.outHeight) {
                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    lp.addRule(RelativeLayout.CENTER_IN_PARENT);
                    imageView.setLayoutParams(lp);
                } else {
                    int w = (int) (op.outWidth * (dm.heightPixels * 1.0f - 48 * 2 * dm.density) / op.outHeight);
                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(w, (int) (dm.heightPixels * 1.0f - 48 * 2 * dm.density));
                    lp.addRule(RelativeLayout.CENTER_IN_PARENT);
                    imageView.setLayoutParams(lp);
                }
            }

            ImageLoader.getInstance().displayImage("file://" + urls[position], imageView, options, null);*/
            container.addView(itemView);
            return itemView;
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position, Object object) {
            super.setPrimaryItem(container, position, object);
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }
}
